package com.example.student_blocket;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

public class MainActivity extends Activity implements OnClickListener {

	private final String LOGIN = Singleton.getInstance().getHOST() + "shop-app/login.php";
	private EditText username;
	private EditText password;
	private Button registerButton;
	private Button loginButton;
	private final Misc misc = new Misc();
	CheckBox usernameCheckBox;
	DatabaseHandler db = new DatabaseHandler(this);
	private final boolean DEBUG = Singleton.getInstance().isDebug();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		setContentView(R.layout.activity_main);
		username = (EditText)findViewById(R.id.usernameInputMain);
		password = (EditText)findViewById(R.id.passwordInputMain);
		registerButton = (Button) findViewById(R.id.registerButton);
		registerButton.setOnClickListener(this);
		
		loginButton = (Button) findViewById(R.id.loginButton);
		loginButton.setOnClickListener(this);
		
		usernameCheckBox = (CheckBox) findViewById(R.id.usernameCheckBox);
		
		String checkBoxStatus = null;
		boolean isOk = false;
		try {
			db.open();
			checkBoxStatus = db.getCheckStatus(1);
			db.close();
			isOk = true;
		} catch (Exception e) {
			isOk = false;
		}
		
		if (!isOk) {
			db.open();
			db.createEntry("", "0");
			db.close();
		}else {
			if(checkBoxStatus.equals("0")){
				usernameCheckBox.setChecked(false);
			}else {
				usernameCheckBox.setChecked(true);
				db.open();
				username.setText(db.getUserName(1));
				db.close();
			}
		}
	}
	
	@Override
	public void onClick(View view) {
		if (view == loginButton) {
			if(usernameCheckBox.isChecked()){
				db.open();
				db.updateEntry(1, username.getText().toString(), "1");
				db.close();
			}else {
				db.open();
				db.updateEntry(1, "", "0");
				db.close();
			}
			if(!DEBUG){
				Singleton.getInstance().setUsername(username.getText().toString());
				new LogIn().execute();
			} else {
				fp_loginbutton();
			}
        }
        if (view == registerButton) {
        	fp_regutton();
        }
	}
	
	private void fp_loginbutton() {
		startActivity(new Intent(MainActivity.this,AdsActivity.class));
	}

	private void fp_regutton() {
		startActivity(new Intent(MainActivity.this,RegisterActivity.class));
	}
	
	/*@Override
	public boolean onCreateOptionsMenu(Menu menu){
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}*/
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    // Inflate the menu items for use in the action bar
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.main, menu);
	    return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item){
			switch(item.getItemId()){
			case R.id.fp_menu_btn_as:
			startActivity(new Intent(MainActivity.this,AboutUsActivity.class));
			return true;
			case R.id.fp_menu_btn_ex:
				finish();
				return true;
			}
			return false;
	}
	
	private class LogIn extends AsyncTask<String, String, Boolean> {
		private ProgressDialog pDialog;
		@Override
		protected void onPreExecute() {
	        super.onPreExecute();
	        
	        pDialog = new ProgressDialog(MainActivity.this);
	        pDialog.setMessage("Loging In...");
	        pDialog.setIndeterminate(false);
	        pDialog.setCancelable(false);
	        pDialog.show();
	    }
		
		@Override
		protected Boolean doInBackground(String... params) {
			boolean loggedIn = false;
			JSONParser jParser = new JSONParser();
			String usernameIn = username.getText().toString();
            String passwordIn = password.getText().toString();
            
            List<NameValuePair> paras = new ArrayList<NameValuePair>();
            paras.add(new BasicNameValuePair("username", usernameIn));
            paras.add(new BasicNameValuePair("password", passwordIn));
 
			JSONObject json = jParser.makeHttpRequest(LOGIN,paras);
	        try {
				int result = json.getInt("affected");
				if (result == 1) {
					loggedIn = true;
				} else {
					loggedIn = false;
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
	        
	        return loggedIn;
		}
		@Override
		protected void onPostExecute(Boolean loggedIn) {
			if (loggedIn) {
				startActivity(new Intent(getApplicationContext(), AdsActivity.class));
				Singleton.getInstance().setUsername(username.getText().toString());
			} else {
				misc.showErrorMessage("Username or password is incorrect!", getApplicationContext());
			}
			pDialog.dismiss();
        }
	}
	
	
}



